/**
 * Wrapper class for SQLiteOpenHelper. 
 * 
 * @author Alican Ozgoren
 * @version 12/14/2012
 */

package edu.brockport.shuttleapp.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import edu.brockport.shuttleapp.Utilities;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager;

public class DatabaseHelper extends SQLiteOpenHelper
{
    //The Android's default system path of your application database.
    private String DB_PATH;
    private static String DB_NAME = "EagleRunSchedule.sqlite";
    
    private SQLiteDatabase myDatabase; 
    private final Context myContext;
    private final int REINSTALL = 2;
    private final int INSTALL = 1; 
    private int installType = 0;
    
    // Takes and keeps a reference of the passed context 
    // in order to access to the application assets and resources.
    //----------------------------------------------------------
    public DatabaseHelper(Context context) 
    {
    	super(context, DB_NAME, null, 1);
        myContext = context;
        DB_PATH = "/data/data/" + myContext.getPackageName() + "/databases/";
    }	
 
    // Creates a empty database on the system and rewrites it with your own database.
    //----------------------------------------------------------
    public void createDataBase() throws IOException
    {
    	boolean dbExist = checkDataBase();
 
    	if(dbExist)
    	{
    		// do nothing - database already exist
    	}
    	else
    	{
        	this.getReadableDatabase();
 
        	try 
        	{
    			copyDataBase();
    		} 
        	catch (IOException e) 
        	{
        		throw new IOException();
        	}
    	}
 
    }
 
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    //----------------------------------------------------------
    private boolean checkDataBase() throws IOException
    {
    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(myContext);
    	PackageInfo packageInfo = null;
    	try
    	{
    		// Get the version code
    		packageInfo = myContext.getPackageManager()
				    .getPackageInfo("edu.brockport.shuttleapp", 0);
    	    int versionCode = packageInfo.versionCode;
    	    
    		if(!prefs.getBoolean("FirstRun", false)) 
        	{
        		SharedPreferences.Editor editor = prefs.edit();
        	    editor.putBoolean("FirstRun", true);
        	    
        	    // Also put version number
        	    editor.putInt("VersionCode", versionCode);
        	    editor.commit();
        	    installType = INSTALL;
        	    return false;
        	}
        	// Check if it's an update (reinstall)
        	else
			if(prefs.getInt("VersionCode", -1) != versionCode)
			{
				SharedPreferences.Editor editor = prefs.edit();
        	    editor.putInt("VersionCode", versionCode);
        	    editor.commit();
        	    installType = REINSTALL;
        	    return false;
			}
			else
			{
				File dbFile = new File(DB_PATH + DB_NAME);
		    	
		    	if(!dbFile.exists())
		    	{
		    		return false;
		    	}
			}
        	
    	}
    	catch(NameNotFoundException e) 
    	{
    		throw new IOException("We do not know what went wrong.");
    	}
    	
    	
    	return true;
    }
 
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    //----------------------------------------------------------
    private void copyDataBase() throws IOException
    {
    	//Open your local db as the input stream
    	InputStream myInput = myContext.getAssets().open(DB_NAME);
 
    	// Path to the just created empty db
    	String outFileName = DB_PATH + DB_NAME;
 
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
 
    	byte[] buffer = new byte[1024];
    	int length;
    	
    	while ((length = myInput.read(buffer)) > 0)
    	{
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
    	
    	if(installType == INSTALL)
    		Utilities.toaster(myContext, "Database was created successfully!");
    	else if(installType == REINSTALL)
    		Utilities.toaster(myContext, "Database was updated successfully!");
    }
 
    //----------------------------------------------------------
    public void open() throws SQLException
    {
    	//Open the database
        String myPath = DB_PATH + DB_NAME;
    	myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }
 
    //----------------------------------------------------------
	public synchronized void close() 
    {
    	if(myDatabase != null) 
    		myDatabase.close();
 
    	super.close();
	}
	
	//----------------------------------------------------------
    public SQLiteDatabase getDatabase()
    {
    	return myDatabase;
    }
 
    //----------------------------------------------------------
	public void onCreate(SQLiteDatabase db) 
	{
		
	}
 
	//----------------------------------------------------------
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
	{
 
	}
}
